package com.hsu.apiinterface.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsu.easyweb.common.ErrorCode;
import com.hsu.easyweb.exception.BusinessException;
import icu.hsu.apisdk.exception.ApiException;
import icu.hsu.apisdk.model.response.ResultResponse;

import java.util.Map;

import static com.hsu.apiinterface.utils.RequestUtils.get;

/**
 * 响应处理工具类，用于将响应转换为指定格式
 * @ClassName: ResponseUtils
 * @author Hsu琛君珩
 * @date 2024-09-08
 * @apiNote
 * @Version: v1.0
 */
public class ResponseUtils {

    /**
     * 将响应字符串转换为Map
     *
     * @param response 响应字符串
     * @return 包含响应数据的Map
     */
    public static Map<String, Object> responseToMap(String response) {
        return new Gson().fromJson(response, new TypeToken<Map<String, Object>>() {
        }.getType());
    }

    /**
     * 处理基础响应
     *
     * @param baseUrl 请求的基础 URL
     * @param params 请求参数对象
     * @return 响应结果对象
     */
    public static <T> ResultResponse baseResponse(String baseUrl, T params) {
        String response = null;
        try {
            response = get(baseUrl, params);
            Map<String, Object> fromResponse = responseToMap(response);
            boolean success = (boolean) fromResponse.get("success");
            ResultResponse baseResponse = new ResultResponse();
            if (!success) {
                baseResponse.setData(fromResponse);
                return baseResponse;
            }
            fromResponse.remove("success");
            baseResponse.setData(fromResponse);
            return baseResponse;
        } catch (ApiException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "构建url异常");
        }
    }
}
